//
//  HMComposeViewController.swift
//  WeiboTT
//
//  Created by 王嘉涛 on 2016/11/22.
//  Copyright © 2016年 王嘉涛. All rights reserved.
//

import UIKit
import SVProgressHUD

private let baseTag = 10000

//定义枚举
enum HMComposeType: Int {
    case Picture = 10000
    case AtSome
    case Topic
    case Emoticon
    case More
}

class HMComposeViewController: UIViewController {

    // 按钮点击监听事件
    @objc private func sendBtnDidClick() {
        print(#function)
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        //POST请求不需要做urlEncode 只有get请求需要处理
        let parameters = ["access_token" : HMUserAccountViewModel.shared.access_token,
                          "status" : textView.text]
        if selector.selectedImages.count == 0 {
            HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters, finished: { (responseObject,error) -> () in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发布微博失败")
                    return
                }
                
                SVProgressHUD.showSuccess(withStatus: "发布微博成功")
            })
        } else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //图片微博
            let imageData = UIImagePNGRepresentation(self.selector.selectedImages.first!)
            HMNetworkTools.shared.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
                //将需要上传的文件的二进制数据拼接到formdata中
                //withFileData: 需要上传的文件的二进制数据
                //name: 服务器接收的字段 "pic"
                //fileName: 服务器存储的名称, 不过新浪微博的服务器会对用户上传的图片按照自己的规则进行处理
                //mimeType: 标识文件类型
                formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "xxxxxxx", mimeType: "application/octet-stream")
            }, progress: nil, success: { (_, result) in
                SVProgressHUD.showSuccess(withStatus: "发布微博成功")
            }, failure: { (_, error) in
                print(error)
                SVProgressHUD.showError(withStatus: "发布图片微博失败")
            })
        }
    }

    @objc internal func toolBarButtonDidClick(btn: UIButton) {
        //通过原始值获取枚举对象  不能够判断可选类型的枚举值
        let enumType = HMComposeType.init(rawValue: btn.tag)!
        switch enumType {
        case .Picture:
            print("选择图片")
        case .AtSome:
            print("@某人")
        case .Topic:
            print("话题")
        case .Emoticon:
            print("选择表情")
        case .More:
            print("更多")
        }
    }

    @objc internal func close() {
        dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 添加控件
        registerNotification()
        setNavBar()
        setTextView()
        setToolBar()
        
        // 添加图片选择控制器
        setSelectorPicture()
    }

    // 注册通知
    private func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    // 监听通知的变化
    @objc private func keyboardChanged(n: Notification) {
        let endFrame = n.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        // 让底部toolBar能动
        let offsetY = -(ScreenHeight - endFrame.origin.y)
        // 跟新约束
        UIView.animate(withDuration: 0.25) {
            self.toolBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offsetY)
            })
            self.view.layoutIfNeeded()
        }
    }
    
    // 懒加载需要的控件 ->底部工具条
    lazy var toolBar: UIStackView = {
        let bottomBar = UIStackView(frame: CGRect.zero)
        // 初始位置和方向
        bottomBar.axis = .horizontal
        bottomBar.distribution = .fillEqually
        return bottomBar
    }()

    // ->发送按钮
    lazy var sendBtn: UIBarButtonItem = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
            // 设置文字
            btn.setTitle("发送", for: .normal)
            //设置背景图片
            btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
            btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
            btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
            btn.setTitleColor(UIColor.darkGray, for: .disabled)
            btn.setTitleColor(UIColor.white, for: .normal)
            btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
        //设置文字颜色
        let barButtonItem = UIBarButtonItem(customView: btn)
        barButtonItem.isEnabled = false

        return barButtonItem
    }()
    
    // ->懒加载textView
    lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFont(ofSize: 18)
        tv.textColor = UIColor.darkGray
        tv.backgroundColor = UIColor(white: 0.9, alpha: 1)
        tv.delegate = self
        tv.keyboardDismissMode = .onDrag
        tv.alwaysBounceVertical = true
        return tv
    }()
    
    lazy var placeHolderLabel: UILabel = {
        let l = UILabel(title: "我是究极涛,我是程序界一股清流~", fontSize: 18, textColor: UIColor.lightGray)
        return l
    }()

    //图片选择器的控制器
    lazy var selector: HMPictureSelectorController = {
        let flowlayout = UICollectionViewFlowLayout()
        flowlayout.itemSize = CGSize(width: selectorCellWidth, height: selectorCellWidth)
        //设置行和列的最小间距
        flowlayout.minimumLineSpacing = selectorMargin
        flowlayout.minimumInteritemSpacing = selectorMargin
        //设置组的内间距
        flowlayout.sectionInset = UIEdgeInsets(top: selectorMargin, left: selectorMargin, bottom: 0, right: selectorMargin)
        let picSel = HMPictureSelectorController(collectionViewLayout: flowlayout)
        //根视图和collectionView不是同一个对象
        //根视图和tableView 是同一个对象
        picSel.view.backgroundColor = UIColor.white
        picSel.collectionView?.backgroundColor = UIColor.white
        return picSel
    }()

    // 移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}

// 遵守TextView的协议
extension HMComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        //判断发布微博按钮的状态
        sendBtn.isEnabled = textView.hasText
        
        //占位文本需要隐藏
        placeHolderLabel.isHidden = textView.hasText
    }
}

// 设置UI界面
extension HMComposeViewController {
    func setSelectorPicture() {
        //***************添加子视图控制器***********
        self.addChildViewController(self.selector)
        //添加控制器的视图
        self.view.addSubview(selector.view)
        //设置约束
        selector.view.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(self.view)
            //设置高度
            make.height.equalTo(ScreenHeight / 3 * 2)
        }
        
    }

    // 设置toolBar
     func setToolBar() {
     
        self.view.addSubview(toolBar)
        // 设置约束
        toolBar.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        // 添加按钮
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        for (index, imageName) in imageNames.enumerated() {
            let btn = UIButton()
            btn.setImage(UIImage(named:imageName), for: .normal)
            btn.backgroundColor = UIColor(white: 0.9, alpha: 1)
            //自适应大小
            btn.sizeToFit()
            //添加到toolBar
            toolBar.addArrangedSubview(btn)
            //监听按钮的点击事件
            btn.addTarget(self, action: #selector(toolBarButtonDidClick(btn:)), for: .touchUpInside)
            //设置tag值
            btn.tag = index + baseTag
        }
    }
    
    // 设置textView
    func setTextView() {
        self.view.addSubview(textView)
        // 添加站位文本
        self.textView.addSubview(placeHolderLabel)
        
        // 设置约束
        textView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            //添加高度约束
            make.height.equalTo(ScreenHeight / 3)
        }
        
        placeHolderLabel.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
    }
    
    // 设置NavBar
    func setNavBar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭",imageName:"",target: self, action: #selector(close))

        // 设置发布按钮
        self.navigationItem.rightBarButtonItem = sendBtn
        // 设置导航条文字.属性文本
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.numberOfLines = 0
        if let userName = HMUserAccountViewModel.shared.userAccount?.name {
            let titleText = "发布微博\n\(userName)"
            titleLabel.text = titleText
            //修改属性文本的属性 使用可变的属性文本 (添加属性), 不可变的属性文本是不能够添加属性的
            let strM = NSMutableAttributedString(string: titleText)
            //获取用户名的范围
            let range = (titleText as NSString).range(of: userName)
            //给用户名添加属性
            strM.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 13), NSForegroundColorAttributeName : UIColor.orange], range: range)
            //给label的属性文本赋值
            titleLabel.attributedText = strM
        } else {
            titleLabel.text = "发布微博"
        }
        
        titleLabel.sizeToFit()
        self.navigationItem.titleView = titleLabel
    }
}
